package com.pro.framework.api.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import lombok.SneakyThrows;

/**
 * hutool toBean 会忽视 transient的属性  比如  transient private String tkPassword;
 */
public class JSONUtils {

    private static ObjectMapper objectMapper;
    private static ObjectReader objectReader;
    private static ObjectWriter objectWriter;

    public static void init(ObjectMapper objectMapper) {
        JSONUtils.objectMapper = objectMapper;
        JSONUtils.objectReader = objectMapper.reader();
        JSONUtils.objectWriter = objectMapper.writer();
    }

    @SneakyThrows
    public static String toString(Object o) {
        return objectWriter.writeValueAsString(o);
    }
    @SneakyThrows
    public static byte[] toBytes(Object o) {
        return objectWriter.writeValueAsBytes(o);
    }

    @SneakyThrows
    public static <T> T fromString(String str, Class<T> clazz) {
        return objectMapper.readerFor(clazz).readValue(str);
    }

    @SneakyThrows
    public static <T> T fromString(String str, TypeReference<T> typeReference) {
        return objectMapper.readerFor(typeReference).readValue(str);
    }

    /**
     * 将可能被转义的 JSON 字符串反转义
     * "{\"name\":\"Tom\",\"age\":18}" 转成 {"name":"Tom","age":18}
     */
    public static String unescapeJson(String body) {
        if (body == null || body.isEmpty()) {
            return body;
        }

        // 判断是否以引号包裹，或者含有转义符
        if ((body.startsWith("\"") && body.endsWith("\"")) || body.contains("\\\"")) {
            try {
                // 用 Jackson 去掉外层引号并反转义
                return objectMapper.readValue(body, String.class);
            } catch (Exception e) {
                // 出错直接返回原始字符串
                return body;
            }
        }

        // 原本就是正常 JSON
        return body;
    }

    public static void main(String[] args) throws Exception {
        String escaped = """
                {"spu_name":"h23121539315","skc_name":"sh2312153931579766","sku_list":[{"sku_code":"I81ynllyzffh"}],"document_sn":"SPMPA420231215003106","version":"SPMP231215009184753","audit_time":"2023-12-18 11:46:43","audit_state":2,"failed_reason":null}
                """;
        String result = unescapeJson(escaped);
        System.out.println(result);  // 输出: {"name":"Tom","age":18}
    }

}
